package com.laundry.user.ui.auth

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.laundry.user.MainActivity
import com.laundry.user.data.repository.UserRepository
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity() {

    private lateinit var userRepository: UserRepository
    private lateinit var phoneEditText: EditText
    private lateinit var codeEditText: EditText
    private lateinit var sendCodeButton: Button
    private lateinit var loginButton: Button
    private lateinit var progressBar: ProgressBar
    private var countDownTimer: CountDownTimer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        userRepository = UserRepository(this)
        
        setupUI()
        setupClickListeners()
    }

    private fun setupUI() {
        val mainLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(80, 120, 80, 120)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
        }

        // 标题
        val titleText = TextView(this).apply {
            text = "洗护帮登录"
            textSize = 28f
            gravity = android.view.Gravity.CENTER
            setPadding(0, 0, 0, 80)
            setTextColor(android.graphics.Color.parseColor("#333333"))
        }

        // 手机号输入
        val phoneLabel = TextView(this).apply {
            text = "手机号"
            textSize = 16f
            setPadding(0, 0, 0, 8)
            setTextColor(android.graphics.Color.parseColor("#666666"))
        }

        phoneEditText = EditText(this).apply {
            hint = "请输入手机号"
            inputType = android.text.InputType.TYPE_CLASS_PHONE
            setPadding(20, 20, 20, 20)
            background = createEditTextBackground()
        }

        // 验证码输入区域
        val codeLayout = LinearLayout(this).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(0, 20, 0, 0)
        }

        val codeLabel = TextView(this).apply {
            text = "验证码"
            textSize = 16f
            setPadding(0, 0, 0, 8)
            setTextColor(android.graphics.Color.parseColor("#666666"))
        }

        codeEditText = EditText(this).apply {
            hint = "请输入验证码"
            inputType = android.text.InputType.TYPE_CLASS_NUMBER
            setPadding(20, 20, 20, 20)
            background = createEditTextBackground()
            layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
        }

        sendCodeButton = Button(this).apply {
            text = "发送验证码"
            textSize = 14f
            setPadding(20, 20, 20, 20)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                marginStart = 20
            }
            background = createButtonBackground("#4CAF50")
            setTextColor(android.graphics.Color.WHITE)
        }

        codeLayout.addView(codeEditText)
        codeLayout.addView(sendCodeButton)

        // 登录按钮
        loginButton = Button(this).apply {
            text = "登录"
            textSize = 18f
            setPadding(0, 30, 0, 30)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                topMargin = 40
            }
            background = createButtonBackground("#2196F3")
            setTextColor(android.graphics.Color.WHITE)
        }

        // 进度条
        progressBar = ProgressBar(this).apply {
            visibility = android.view.View.GONE
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                gravity = android.view.Gravity.CENTER_HORIZONTAL
                topMargin = 20
            }
        }

        // 添加到主布局
        mainLayout.addView(titleText)
        mainLayout.addView(phoneLabel)
        mainLayout.addView(phoneEditText)
        mainLayout.addView(codeLabel)
        mainLayout.addView(codeLayout)
        mainLayout.addView(loginButton)
        mainLayout.addView(progressBar)

        setContentView(mainLayout)
    }

    private fun setupClickListeners() {
        sendCodeButton.setOnClickListener {
            sendVerificationCode()
        }

        loginButton.setOnClickListener {
            login()
        }
    }

    private fun sendVerificationCode() {
        val phone = phoneEditText.text.toString().trim()
        
        if (phone.isEmpty()) {
            showToast("请输入手机号")
            return
        }

        if (!isValidPhone(phone)) {
            showToast("请输入正确的手机号")
            return
        }

        sendCodeButton.isEnabled = false
        progressBar.visibility = android.view.View.VISIBLE

        lifecycleScope.launch {
            val result = userRepository.sendVerificationCode(phone)
            
            progressBar.visibility = android.view.View.GONE
            
            if (result.isSuccess) {
                showToast("验证码已发送")
                startCountDown()
            } else {
                showToast(result.exceptionOrNull()?.message ?: "发送失败")
                sendCodeButton.isEnabled = true
            }
        }
    }

    private fun login() {
        val phone = phoneEditText.text.toString().trim()
        val code = codeEditText.text.toString().trim()

        if (phone.isEmpty()) {
            showToast("请输入手机号")
            return
        }

        if (code.isEmpty()) {
            showToast("请输入验证码")
            return
        }

        loginButton.isEnabled = false
        progressBar.visibility = android.view.View.VISIBLE

        lifecycleScope.launch {
            val result = userRepository.login(phone, code)
            
            progressBar.visibility = android.view.View.GONE
            loginButton.isEnabled = true
            
            if (result.isSuccess) {
                showToast("登录成功")
                startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                finish()
            } else {
                showToast(result.exceptionOrNull()?.message ?: "登录失败")
            }
        }
    }

    private fun startCountDown() {
        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val seconds = millisUntilFinished / 1000
                sendCodeButton.text = "${seconds}s后重发"
            }

            override fun onFinish() {
                sendCodeButton.text = "发送验证码"
                sendCodeButton.isEnabled = true
            }
        }.start()
    }

    private fun isValidPhone(phone: String): Boolean {
        return phone.matches(Regex("^1[3-9]\\d{9}$"))
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    private fun createEditTextBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.setStroke(2, android.graphics.Color.parseColor("#E0E0E0"))
        drawable.cornerRadius = 8f
        return drawable
    }

    private fun createButtonBackground(color: String): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.parseColor(color))
        drawable.cornerRadius = 8f
        return drawable
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
    }
}
